package com.huanghwh.sync.core.service.impl;

import com.huanghwh.sync.core.entity.SyncResult;
import com.huanghwh.sync.core.service.ISyncCoreService;
import com.huanghwh.sync.core.service.ITableSyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Author: huanghwh
 * @Date: 2021/12/22 10:29
 * @Description:
 */
@Slf4j
@Service
public class TableSyncServiceImpl implements ITableSyncService {

    @Autowired
    private ISyncCoreService syncCoreService;


    @Value("${datasource.config.origin}")
    private String originDbConfigName;

    @Value("${datasource.config.target}")
    private String targetDbConfigName;

    @Value("${datasource.table}")
    private String tableNames;


    /**
     * 执行同步操作
     *
     * @return
     * @Author huanghwh
     * @Date 2021/12/22 10:30
     */
    @Override
    public boolean startSync(Integer minute) {
        // 查询需要同步的表
        if (StringUtils.isBlank(tableNames)) {
            throw new NullPointerException("datasource.table is required");
        }
        String[] tableList = tableNames.split(",");
        for (String tableName : tableList) {
            this.execute(tableName, minute);
        }
        return true;
    }


    /**
     * 调用执行同步接口
     *
     * @param tableName
     * @param minute
     * @return
     * @Author huanghwh
     * @Date 2021/12/22 11:10
     */
    private void execute(String tableName, Integer minute) {
        SyncResult syncResult = null;
        try {
            // 同步核心
            syncResult = syncCoreService.executeSync(originDbConfigName, targetDbConfigName, tableName, minute);
        } catch (Exception e) {
            log.error("Table: {} 同步失败", tableName);
            return;
        }
        log.info("同步完成: {}，{}", tableName, syncResult.toString());
    }
}
